<template>
  <div class="app-container">
    <el-card class="box-card">
      <h2 class="text-2xl mb-5">碎片信息</h2>
      <div class="flex items-center">
        <p v-if="!headerList.length">----暂无数据</p>
        <div class="flex">
          <div v-for="item in headerList" :key="item.id" class="mr-4">
            <el-image :src="item.chip.icon" fit="fill" :lazy="true" class="chipIcon"></el-image>
            <p class="text-center">{{ item.chip.name }} * {{ item.count }}</p>
          </div>
        </div>
        <el-button size="default" type="primary" @click="handleEditShard">编辑</el-button>
      </div>

    </el-card>


    <el-card class="box-card">
      <h2 class="text-2xl mb-5">奖励信息</h2>
      <el-button size="default" type="primary" @click="handleAdd">新增</el-button>

      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="mt-3"
        stripe
        style="width: 100%"
        tooltip-effect="dark"
      >
        <!-- <el-table-column :index="indexMethod" label="序号" prop="user_code" type="index" width="120px"></el-table-column> -->
        <el-table-column label="奖励id" prop="detail.id"></el-table-column>
        <el-table-column label="奖励名称" prop="detail.name"></el-table-column>
        <el-table-column label="奖励图片" prop="detail.picture">
          <template slot-scope="scoped">
            <el-image :lazy="true" :src="scoped.row.detail.picture" class="imageStyle" fit="fill"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="奖励价值" prop="detail.price">
          <template slot-scope="{row}">
            {{ row.reward_type === 'gift' ? row.detail.price : '--'}}
          </template>
        </el-table-column>
        <el-table-column label="奖励有效期" prop="count">
          <template slot-scope="{row}">
            {{ row.reward_type === 'gift' ? '--' : row.count}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="等级" prop="level"></el-table-column> -->
        <el-table-column label="更新时间" prop="updated_at"></el-table-column>
        <el-table-column label="状态" prop="is_open">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_open === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleOpen(scope.row)"
            >{{ scope.row.is_open === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleSDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <cus-pagination
        v-show="total > 0"
        :limit.sync="listQuery.perPage"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getTableData"
      />
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="120px" size="normal">
        <el-form-item v-if="!isEdit" label="奖励类型" prop="reward_type">
          <el-select v-model="formData.reward_type" clearable filterable placeholder="请选择奖励类型" @change="handleChange">
            <el-option
              v-for="item in rewardType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.reward_type === 'gift'" :label="isEdit?'选择替换礼物':'选择礼物'" prop="reward_id">
          <el-select 
            v-model="formData.reward_id" 
            remote 
            clearable 
            filterable 
            :remote-method="remoteMethod" 
            placeholder="请选择礼物" 
            @clear="clear"
          >
            <el-option
              v-for="item in menuList1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.reward_type === 'product'" :label="isEdit?'选择替换奖励':'选择奖励'" prop="reward_id">
          <el-select 
            v-model="formData.reward_id" 
            remote 
            clearable 
            filterable 
            :remote-method="remoteMethod2" 
            placeholder="请选择奖励" 
            @clear="clear2"
          >
            <el-option
              v-for="item in menuList2"
              :key="item.id"
              :label="item.product_name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.product_name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.reward_type=== 'product'" label="奖励有效期" prop="count">
          <el-input type="number" v-model="formData.count" @input="handleInput">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="奖励等级" prop="level">
          <el-input
            v-model="formData.level"
            placeholder="请输入奖励等级"
          />
        </el-form-item> -->
        <el-form-item label="状态" prop="sort">
          <el-radio-group v-model="formData.is_open">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleOnSubmit">确定</el-button>
            </span>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible2"
      title="编辑碎片信息"
      width="600px"
      @close="closeDialog2"
    >
      <el-form ref="form2" :inline="false" :model="formShardData" label-width="120px" size="normal">
        <el-form-item
          v-for="(domain, index) in formShardData.domains"
          :key="index"
        >
          <el-form-item :label="'选择碎片' + (index+1)" :prop="'domains.' + index + '.chip_id'" :rules="{
            required: true, message: '不能为空', trigger: 'change'
          }"
          >
            <el-select v-model="domain.chip_id"
                       class="filter-item marginRB10"
                       filterable
                       placeholder="请选择"
            >
              <el-option
                v-for="item in selectList2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="'碎片数量'" :prop="'domains.' + index + '.count'" :rules="{
            required: true, message: '不能为空', trigger: 'blur'
          }"
          >
            <el-input type="number" v-model="domain.count" style="width:200px;"></el-input>
            <i class="el-icon-circle-plus-outline" style="font-size: 20px;cursor: pointer" @click="addDomain(domain)"
            ></i>
            <i v-if="formShardData.domains.length>1" class="el-icon-remove-outline"
               style="font-size: 20px;cursor:pointer;" @click="removeDomain(domain)"
            ></i>
          </el-form-item>

        </el-form-item>


      </el-form>

      <span slot="footer">
                <el-button @click="dialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="handleShardSubmit">确定</el-button>
            </span>
    </el-dialog>

  </div>
</template>

<script>
import { upgradeInfo, upgradeEdit, upgradeAdd, upgradeChip, upgradeChange, productList, chipList } from '@/api/sunGame/sunGame'
// 礼物下拉数据
import { getData } from '@/api/roomGift/giftList'

export default {
  name: 'ultimateConfig',
  components: {},
  data() {
    return {
      formShardData: {
        domains: [{
          count: '',
          chip_id: undefined
        }],
      },
      dialogVisible2: false,
      selectList2: [
        { key: -1, lab: '全部状态' },
        { key: 1, lab: '启用 ' },
        { key: 2, lab: '禁用' }
      ],
      dialogVisible: false,
      formData: {
        reward_type: undefined,
        reward_id: undefined,
        count: undefined,
        // level: undefined,
        is_open: 1,
        id: undefined,
        type: 2
      },
      rules: {
        reward_type: [{ required: true, message: '请选择奖励类型', trigger: 'blur' }],
        reward_id: [{ required: true, message: '请选择奖励', trigger: 'blur' }],
        // level: [{ required: true, message: '请输入奖励等级', trigger: 'blur' }],
        count: [{ required: true, message: '请输入奖励有效期', trigger: 'blur' }],
      },
      loading: false,
      tableData: [],
      listQuery: {
        page: 1,
        perPage: 10,
        type: 2
      },
      total: 1,
      fileList: [],
      dialogTitle: undefined,
      headerList: [],
      rewardType: [
        {
          value: 'gift',
          label: '礼物'
        },
        {
          value: 'product',
          label: '装扮'
        },
      ],
      isEdit: false,
      menuList1: [],
      menuList2: [],
      optionQuery: {
        page: 1,
        page_size: 50,
        cate_id: 0,
        style_id: 0
      }
    }
  },
  created() {
    this.getTableData()
    this.handleGetData()
    this.handleGetProductList()
    this.getChipList()
  },
  methods: {
    handleGetData() {
      getData(this.optionQuery).then(res => {
        res.data.data.map(item => {
          
          item.name = item.name + `(${item.price}M豆)`
          
        })
        this.menuList1 = res.data.data
      })
    },
    handleGetProductList() {
      productList(this.optionQuery).then(res => {
        this.menuList2 = res.data.data
      })
    },
    async getChipList() {
      const { data, code } = await chipList({
        page: 1,
        perPage: 9000
      })
      if (code === 200) {
        this.selectList2 = data.list
      }

    },
    handleShardSubmit() {
      
      upgradeChip({
        type: 2,
        list: this.formShardData.domains
      }).then(res => {
        if(res.code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.dialogVisible2 = false
          this.getTableData()
        }
      })
    },
    addDomain() {
      this.formShardData.domains.push({
        count: '',
        chip_id: undefined
      })
    },
    removeDomain(item) {
      let index = this.formShardData.domains.indexOf(item)
      if (index !== -1) {
        this.formShardData.domains.splice(index, 1)
      }
    },
    handleEditShard() {
      this.formShardData.domains = JSON.parse(JSON.stringify(this.headerList))
      this.dialogVisible2 = true
    },
    indexMethod(index) {
      return this.total - (this.listQuery.page - 1) * this.listQuery.perPage - index
    },
    // 网络请求
    /**
     * getTableData
     * @desc 获取表格数据
     */
    async getTableData() {
      this.loading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = !this.listQuery[key] ? undefined : this.listQuery[key]
      }
      const { data, code } = await upgradeInfo(this.listQuery)
      if (code === 200) {

        this.tableData = data.list
        this.headerList = data.header
        this.total = data.meta.total
      }
      this.loading = false

    },
    closeDialog() {
      if (this.$refs['form']) {
        this.$refs['form'].clearValidate() // 清除整个表单的校验
        this.$refs['form'].resetFields() // 清除整个表单的校验
      }
      this.fileList = []
      this.formData = {
        reward_type: undefined,
        reward_id: undefined,
        count: undefined,
        level: undefined,
        is_open: 1,
        id: undefined,
        type: 2
      }
    },
    closeDialog2() {
      if (this.$refs['form2']) {
        this.$refs['form2'].clearValidate() // 清除整个表单的校验
        this.$refs['form2'].resetFields() // 清除整个表单的校验
      }
      this.formShardData = {
        domains: [{
          count: '',
          chip_id: undefined
        }],
      }
    },
    handleOnSubmit() {

      this.$refs['form'].validate(valid => {
        if (valid) {

          for (let key in this.formData) {
            this.formData[key] = !this.formData[key] ? undefined : this.formData[key]
          }
          if(!this.formData.is_open) {
            this.formData.is_open = 0
          }
          if (this.formData.id) {
            upgradeEdit(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          } else {
            upgradeAdd(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          }

        }
      })
    },
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑'
      if(row.reward_type === 'gift') {
        this.optionQuery.id = row.reward_id
        this.handleGetData(this.optionQuery)
      }
      if(row.reward_type === 'product') {
        this.optionQuery.id = row.reward_id
        this.handleGetProductList(this.optionQuery)
      }
      this.formData = JSON.parse(JSON.stringify(row))
      this.formData.type = 1
      this.dialogVisible = true
    },
    handleOpen(row) {
      this.$confirm(`确认${row.is_open === 1 ? '禁用' : '启用'}操作？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        upgradeChange({
          id: row.id,
          type: 1
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogVisible = false
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleSDelete(row) {
      this.$confirm('此操作不可恢复，是否继续删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        upgradeChange({
          id: row.id,
          type: 0
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogVisible = false
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        perPage: 10,
        type: 2
      }
      this.getTableData()
    },
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.optionQuery.gift_name = undefined
      this.optionQuery.name = undefined
      this.optionQuery.id = undefined
      this.handleGetData()
      this.handleGetProductList()
    },
    remoteMethod(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.gift_name = query
        this.handleGetData(this.optionQuery)
      }
    },
    remoteMethod2(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.name = query
        this.handleGetProductList(this.optionQuery)
      }
    },
    clear() {
      this.optionQuery = {
        page: 1,
        page_size: 50,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetData(this.optionQuery)
    },
    clear2() {
      this.optionQuery = {
        page: 1,
        page_size: 50,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetProductList(this.optionQuery)
    },
    handleInput(val) {
      if(val < 1) {
        this.formData.count = undefined
      }
      if(val.includes('.')) {
        this.formData.count = val.replace('.', '')
      }
    },
    handleChange() {
      this.formData.reward_id = undefined
    }
  }
}
</script>

<style lang="scss" scoped>

.imageStyle {
  width: 150px;
}
.chipIcon {
  width: 80px;
  height: 80px;
  overflow: hidden;
}


.item {
  width : 100px;
}

.formItemBox {
  display     : flex;
  align-items : center;
  flex-wrap   : wrap;

  width       : 100%;
  overflow    : hidden;
}

::v-deep {
  .formItemBox {
    .el-form-item {
      width : 50% !important;
    }
  }

}

</style>

